<template>
  <div class="fa-image-fill">
    <WidgetPlaceholder
      v-show="!image"
      :data="data"
      :icon="loading ? 'el-icon-loading' : 'fa-icon-upload'"
      text="上传图片"
      @click.native="areaClick"
    />

    <div v-show="image" class="image-info">
      <ElPopover
        class="name"
        popper-class="fa-image-fill__preview"
        placement="top-start"
        width="200"
        trigger="hover"
        :disabled="!image"
      >
        <span :title="data.image.name" slot="reference">{{ data.image.name }}</span>

        <img class="image" :src="image" />
      </ElPopover>

      <a class="action el-icon-refresh-right" title="重新上传" @click="areaClick"></a>
      <a class="action el-icon-close" title="删除图片" @click="() => data.clear()"></a>
    </div>

    <input ref="input" class="fa-image-fill__input" type="file" :accept="accept" @change="fileChange" />
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, toRefs } from 'vue'
import { Viewer } from '@/types'
import { Widget } from '@/models'
import useUpload from './useUpload'
import WidgetPlaceholder from '@/components/widget-base/WidgetPlaceholder.vue'

/** 图片填写 */
export default defineComponent({
  name: 'FaImageFill',

  components: { WidgetPlaceholder },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 文档查看组件 */
    viewer: {
      type: Object as PropType<Viewer>,
      required: true
    }
  },

  setup(props) {
    const { data, viewer } = toRefs(props)

    return useUpload({
      data,
      viewer
    })
  }
})
</script>

<style lang="scss">
.fa-image-fill {
  .fa-widget-placeholder {
    height: 32px;
    background: #fff;
    border: $border-solid;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      border-color: $border-color-dark;
    }

    &:active {
      background: $background-color-secondary;
    }
  }

  .image-info {
    display: flex;
    align-items: center;

    .name {
      flex: 1;
      font-size: 12px;
      @include text-ellipsis;
    }

    .action {
      margin-left: 8px;
      color: $color-info;
      font-size: 16px;
      cursor: pointer;
      transition: color 0.25s ease-in-out;

      &:hover {
        color: $color-primary;
      }
    }
  }

  &__input {
    position: absolute;
    width: 0;
    height: 0;
    opacity: 0;
  }

  &__preview {
    .image {
      display: block;
      max-width: 100%;
    }
  }
}
</style>
